import React from 'react'
import { connect } from 'dva'
import router from 'umi/router'
import { formatMessage } from 'umi/locale'
import { Input, Button } from 'antd'
import PageHeaderWrapper from '@/components/PageHeaderWrapper'

@connect(({ projectHall }) => ({
  projectHall
}))
export default class extends React.PureComponent {

  componentDidMount() {
    const { dispatch } = this.props

    dispatch({
      type: 'projectHall/fetchProject',
      payload: { page: 0 }
    })
    dispatch({
      type: 'user/fetchDepartment'
    })
  }

  handleNewProject = () => {
    const { dispatch } = this.props

    dispatch({
      type: 'projectHall/save',
      payload: { visible: true, profile: {} }
    })
  }

  handleTabChange = key => {
    const { dispatch, match } = this.props

    let status = '0'
    switch (key) {
      case 'search':
        status = null
        router.push(`${match.url}/search`)
        break
      case 'on':
        status = '1'
        router.push(`${match.url}/on`)
        break
      case 'complete':
        status = '2'
        router.push(`${match.url}/complete`)
        break
      case 'end':
        status = '3'
        router.push(`${match.url}/end`)
        break
      default:
        break
    }
    dispatch({
      type: 'projectHall/fetchProject',
      payload: {
        status
      }
    })
  }

  handleFormSubmit = values => {
    const { dispatch, match } = this.props

    router.push(`${match.url}/search`)

    const payload = {}
    if (values) {
      Object.assign(payload, { project_name: values })
    }
    dispatch({
      type: 'projectHall/fetchProject',
      payload
    })
  }

  render() {
    const { match, children, location } = this.props

    const tabList = [{
      key: 'search',
      tab: formatMessage({ id: 'menu.pro.search' }, {})
    }, {
      key: 'on',
      tab: formatMessage({ id: 'menu.pro.on' }, {}),
    }, {
      key: 'complete',
      tab: formatMessage({ id: 'menu.pro.complete' }, {}),
    }, {
      key: 'end',
      tab: formatMessage({ id: 'menu.pro.end' }, {}),
    }]

    const mainSearch = (
      <div style={{ textAlign: 'center' }}>
        <Input.Search
          placeholder="请输入要搜索的项目名称"
          enterButton="搜索"
          size="large"
          onSearch={this.handleFormSubmit}
          style={{ maxWidth: 522 }}
        />
        <Button onClick={this.handleNewProject} type="primary" ghost size="large" icon="form" style={{ marginLeft: 12 }}>
          新建
        </Button>
      </div>
    )

    return (
      <PageHeaderWrapper
        content={mainSearch}
        tabList={tabList}
        tabActiveKey={
          location.pathname.replace(`${match.path}/`, '').replace('/profile', '')
        }
        onTabChange={this.handleTabChange}
      >
        {children}
      </PageHeaderWrapper>
    )
  }
}